package server;
import java.util.*;
import java.io.*;
import msgs.*;
/**
 * Blocks users at users' requests.
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */
public class Blocker extends Thread implements TTConstants {
	private BlockMsg bmsg;
	
	public Blocker(ClientMsg cmsg) {
		this.bmsg = (BlockMsg) cmsg;
	}
	
	public void run() {
		// auth
		if (!(Arrays.equals(bmsg.getClientKey(), TTServer.connTable.get(bmsg.getName()).getClientKey()))) {
			bmsg.setResponse(Responses.DENY);
			ClientSender.outQ.add((ClientMsg) bmsg);
			return;
		}
		
		// switch on what they want to do
		switch(bmsg.getAction()) {
		case BLOCK:
			// add to the blocklist
			// check if they HAVE a blocklist
			if (!(TTServer.blockList.containsKey(bmsg.getName()))) {
				synchronized(TTConstants.lock) {
					ArrayList<String> al = new ArrayList<String>();
					al.add(bmsg.getWantsBlock());
					// put that in the hashtable and page to disk
					TTServer.blockList.put(bmsg.getName(), al);
					TTServer.writeHash(new File("data/blockList.dat"), TTServer.blockList);
				}
				break;
			}
			else {
				// get the block list, check to see if the user is already there
				// else, add it, write to disk
				if (!(TTServer.blockList.get(bmsg.getName()).contains(bmsg.getWantsBlock()))) {
					synchronized(TTConstants.lock) {
						TTServer.blockList.get(bmsg.getName()).add(bmsg.getWantsBlock());
						TTServer.writeHash(new File("data/blockList.dat"), TTServer.blockList);
					}
				}
			}
			bmsg.setResponse(Responses.OK);
			ClientSender.outQ.add((ClientMsg) bmsg);
			return;
		case UNBLOCK:
			// auth
			if (!(Arrays.equals(bmsg.getClientKey(), TTServer.connTable.get(bmsg.getName()).getClientKey()))) {
				bmsg.setResponse(Responses.DENY);
				ClientSender.outQ.add((ClientMsg) bmsg);
				return;
			}
			
			// check if they have a blocklist
			// if not, just deny.
			if (!(TTServer.blockList.containsKey(bmsg.getName()))) {
				bmsg.setResponse(Responses.DENY);
				ClientSender.outQ.add((ClientMsg) bmsg);
				return;
			}
			else {
				// check if they are even blocked... if yes, remove, else
				// just return. as always, write to disk
				if (TTServer.blockList.get(bmsg.getName()).contains(bmsg.getWantsBlock())) {
					synchronized (TTConstants.lock) {
						TTServer.blockList.get(bmsg.getName()).remove(bmsg.getWantsBlock());
						TTServer.writeHash(new File("data/blockList.dat"), TTServer.blockList);
					}
				}
				bmsg.setResponse(Responses.OK);
				ClientSender.outQ.add((ClientMsg) bmsg);
				return;
			}
		}
	}
}
